from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *

BUTTON_HEIGHT = 28
BUTTON_WIDTH = 28

MAX_ICON = QIcon('icon/max.svg')
MIN_ICON = QIcon('icon/min.svg')
RESTORE_ICON = QIcon('icon/restore.svg')
CLOSE_ICON = QIcon('icon/close.svg')

class TitleBar(QWidget):
    def __init__(self, parent, title:str = "WindowTitle") -> None:
        super().__init__(parent)
        self.click_pos:QPoint = None
        self.is_max:bool = False
        self.last_geometry:QRect = None

        self.title = QLabel(title)
        self.title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.title.setObjectName("WindowTitle")

        self.max_button = QPushButton(MAX_ICON, "")
        self.max_button.clicked.connect(self.maxButtonClickedSlot)
        self.max_button.setObjectName("Max")

        self.min_button = QPushButton(MIN_ICON, "")
        self.min_button.clicked.connect(self.window().showMinimized)
        self.min_button.setObjectName("Min")

        self.close_button = QPushButton(CLOSE_ICON, "")
        self.close_button.clicked.connect(self.window().close)
        self.close_button.setObjectName("Close")

        for button in (self.max_button, self.min_button, self.close_button):
            button.setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT)
            button.setFlat(True)
            button.setFocusPolicy(Qt.FocusPolicy.NoFocus)

        spaceWidget = QWidget()
        spaceWidget.setFixedSize(BUTTON_WIDTH * 3, BUTTON_HEIGHT)

        layout = QHBoxLayout(self)
        layout.addWidget(spaceWidget)
        layout.addWidget(self.title)
        layout.addWidget(self.min_button)
        layout.addWidget(self.max_button)
        layout.addWidget(self.close_button)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setObjectName("TitleBar")
        self.setLayout(layout)

    def mouseMoveEvent(self, event: QMouseEvent) -> None:
        if self.is_max:
            return
        self.window().move((event.globalPosition() - self.click_pos).toPoint())

    def mousePressEvent(self, event: QMouseEvent) -> None:
        self.click_pos = self.mapToParent(event.position())
    
    def mouseDoubleClickEvent(self, event: QMouseEvent) -> None:
        self.maxButtonClickedSlot()

    def maxButtonClickedSlot(self):
        if self.is_max:
            self.max_button.setIcon(MAX_ICON)
            self.window().showNormal()
        else:
            self.max_button.setIcon(RESTORE_ICON)
            self.window().showMaximized()
        self.is_max = not self.is_max
    
    def paintEvent(self, event: QPaintEvent) -> None:
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PrimitiveElement.PE_Widget, opt, p, self)
        return super().paintEvent(event)

